package top.mcwebsite.playandroid.lib.markdown.render

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.ast.ASTNode
import top.mcwebsite.playandroid.lib.markdown.BlockVerticalPadding

@Composable
fun CodeBlock(
    markdownState: MarkdownState,
    astNode: ASTNode,
) {
    Box(
        modifier = Modifier
            .padding(vertical = BlockVerticalPadding)
            .background(color = Color(0xFFDDDDDD), shape = MaterialTheme.shapes.medium)
            .fillMaxWidth()
    ) {
        Text(text = remember(astNode) {
            getCodeBlock(astNode, markdownState)
        }, modifier = Modifier.padding(8.dp))
    }
}

fun getCodeBlock(astNode: ASTNode, markdownState: MarkdownState): String {
    val sb = StringBuilder()
    for (node in astNode.children) {
        when (node.type) {
            MarkdownTokenTypes.CODE_FENCE_CONTENT -> {
                sb.append(markdownState.text.substring(node.startOffset, node.endOffset))
            }

            MarkdownTokenTypes.EOL -> {
                sb.appendLine()
            }
        }
    }
    return sb.toString().trim()
}